<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use app\common\model\Goods;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        //未领奖  已领奖  已弃奖
        $typeList = [
            'tobepaid'  => '待付款',
            'tobesend'  => '待发货',
            'tobereceived'  => '待收货',
            'done'      => '已完成',
            'cancel'    => '已取消',
        ];

        $this->view->assign("typeList", $typeList);
        $this->assignconfig('typeList',$typeList);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $stateDict = [
            1 => '正常',
            2 => '完成',
            3 => '取消',
        ];
        $pay_stateDict = [
            0 => '待付款',
            1 => '已付款',
        ];
        $ship_stateDict = [
            0 => '待发货',
            1 => '已发货',
            2 => '已收货',
        ];

        $this->assignconfig('stateDict',$stateDict);
        $this->assignconfig('pay_stateDict',$pay_stateDict);
        $this->assignconfig('ship_stateDict',$ship_stateDict);

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }


            $map = [];
            $status = $this->request->request("type");
            switch ($status){
                case 'tobepaid':
                    //待付款
                    $map['state'] = 1;
                    $map['pay_state'] = 0;
                    break;
                case 'tobesend':
                    //待发货
                    $map['state'] = 1;
                    $map['pay_state'] = 1;
                    $map['ship_state'] = 0;
                    break;
                case 'tobereceived':
                    //待收货
                    $map['state'] = 1;
                    $map['pay_state'] = 1;
                    $map['ship_state'] = 1;
                    break;
                case 'done':
                    //已完成
                    $map['state'] = 2;
                    break;
                case 'cancel':
                    //已取消
                    $map['state'] = 3;
                    break;
                default:
                    break;

            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                /*$row['state'] = isset($stateDict[$row['state']]) ? $stateDict[$row['state']] : $row['state'];
                $row['pay_state'] = isset($pay_stateDict[$row['pay_state']]) ? $pay_stateDict[$row['pay_state']] : $row['pay_state'];
                $row['ship_state'] = isset($ship_stateDict[$row['ship_state']]) ? $ship_stateDict[$row['ship_state']] : $row['ship_state'];*/
                if ($row['state'] == 1){
                    if ($row['pay_state'] == 1){
                        if ($row['ship_state'] == 1){
                            $row['type'] = '待收货';
                        }else{
                            $row['type'] = '待发货';
                        }
                    }else{
                        $row['type'] = '待付款';
                    }
                }elseif ($row['state'] == 2){
                    $row['type'] = '已完成';
                }elseif ($row['state'] == 3){
                    $row['type'] = '已取消';
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查看
     * @throws \think\exception\DbException
     */
    public function show($ids = null)
    {
        $row = $this->model->get($ids,'orderProducts');
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 发货
     * @throws \think\exception\DbException
     */
    public function delivery($ids = null){

        $row = $this->model
            ->get($ids,'orderProducts');

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row['pay_state'] != 1 || $row['ship_state'] != 0) $this->error('非法操作！');

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params['is_nomal_virtual'] == 1 && (!$params['logi_code'] || !$params['logi_no'])){
                $this->error('请填写物流信息！');
            }

            if ($params) {
                //获取发货单model
                $deliveryModel = new \app\admin\model\Delivery();
                $deliveryItemsModel = new \app\admin\model\DeliveryItems();

                $delivery_sn = get_sn(8); //发货单号自动生成
                $deliveryData = [
                    'delivery_sn'   =>  $delivery_sn,
                    'order_sn'      =>  $params['order_sn'],
                    'logi_code'     =>  $params['logi_code'],
                    'logi_no'       =>  $params['logi_no'], //物流单号
                    'is_nomal_virtual' =>  $params['is_nomal_virtual'], //1=普通发货单 2=虚拟发货单（虚拟商品不用填写快递单号）
                    'remark'        =>  $params['remark'],
                    'status'        =>  2, //状态 1=准备发货 2=已发货 3=已确认 4=其他
                    'ship_name'     =>  $row['ship_name'],
                    'ship_mobile'   =>  $row['ship_mobile'],
                    'ship_area'     =>  $row['ship_area'],
                    'ship_detail'   =>  $row['ship_detail'],
                ];

                $orderData = [
                    'ship_state'    => 1,
                ];
                $goodsModel = new Goods();
                Db::startTrans();
                try {
                    //添加发货单
                    $deliveryModel->save($deliveryData);

                    $itemsData = [];
                    if ($row['orderProducts']){
                        foreach ($row['orderProducts'] as $k => $v){
                            $arr = [
                                'delivery_sn'   => $delivery_sn,
                                'goods_id'      => $v['goods_id'],
                                'products_id'   => $v['products_id'],
                                'bn'            => $v['bn'],
                                'sn'            => $v['sn'],
                                'name'          => $v['name'],
                                'num'           => $v['num'],
                            ];
                            //发货后，减库存
                            $ret = $goodsModel->changeStock($v['products_id'],'send',$v['num']);
                            $itemsData[] = $arr;
                        }
                    }
                    //添加发货单下的商品
                    $deliveryItemsModel->saveAll($itemsData);

                    //更新发货状态
                    $row->save($orderData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                //发货成功 设置延时确认收货
                if (Config::get('site.auto_confirm_days') > 0){
                    $days = Config::get('site.auto_confirm_days');
                    //自动弃奖
                    $delay = $days * 24 * 60 *60;
                    $job = 'AutoConfirm';
                    $queue = 'autoconfirm';
                    $isPushed = Queue::later($delay,$job,$params['order_sn'],$queue);
                }

                $this->success('发货成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
